﻿using Newtonsoft.Json.Linq;
using Qianke.Core.Common;
using Qianke.Core.Common.Models;
using System.Net.Http.Headers;

namespace Qianke.Core.Saas.Application.Common
{
    public static class HttpHelperExtensions
    {
        public static async Task<ReturnInfo> CallApi<TResultData>(this HttpHelper httpHelper, string url, object paramBody, Action<HttpContentHeaders> optionHeader = null)
        {
            return await httpHelper.Post<ReturnInfoData<TResultData>>(url, paramBody.ToJson(), optionHeader);
        }

        public static Task<ReturnInfo> TokenCallApi<TResultData>(this HttpHelper httpHelper, string url, object paramBody, Action<HttpContentHeaders> optionHeader = null)
        {
            var jToken = paramBody?.ToJson().ToObject<JToken>() ?? new JObject();
            if (string.IsNullOrEmpty(jToken["Token"].SafeToString()))
            {
                jToken["Token"] = httpHelper.LazyServiceProvider.LazyGetService<SaasRequestInfo>()?.Token;
            }

            return CallApi<TResultData>(httpHelper, url, jToken, optionHeader);
        }

        public static Task<ReturnInfo> CallChildApi<TResultData>(this HttpHelper httpHelper, string url, object paramBody, Action<HttpContentHeaders> optionHeader = null)
        {
            JToken jToken = paramBody?.ToJson().ToObject<JToken>() ?? new JObject();
            if (jToken["OrganId"].ToInt64(0L) == 0)
            {
                var saasRequestInfo = httpHelper.LazyServiceProvider.LazyGetService<SaasRequestInfo>();
                if (!string.IsNullOrEmpty(saasRequestInfo.Token))
                {
                    jToken["Token"] = saasRequestInfo.Token;
                }

                jToken["OrganId"] = saasRequestInfo.TokenModel.OrganId;
                jToken["ManagerId"] = saasRequestInfo.TokenModel.Id;
            }

            return CallApi<TResultData>(httpHelper, url, jToken, optionHeader);
        }
    }
}
